package com.example.dinner;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.view.accessibility.AccessibilityViewCommand;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;


public class FragmentDinner extends Fragment implements View.OnClickListener {

    private RecyclerView listRl;
    private MyAdapter myAdapter;
    final int MSG_0x12 = 0x12;//result
    private TextView tvDate;
    private TextView tvMenu1;
    private TextView tvMenu2;
    private TextView tv_comment;
    private TextView tv_choosed;
    private EditText etNo;
    private EditText etName;
    private Button btnOrder;
    private LinearLayout llMenu1;
    private LinearLayout llMenu2;
    private ImageView imgMenu1;
    private ImageView imgMenu2;
    DinnerBean dinnerBean;
    String menu;
    String dinnerResponse="";//带有menuID，用于请求后台记录

    private AlertDialog.Builder builder;

    ArrayList arrayList = new ArrayList<ListBeans.ListBean>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {

            try {
                switch (msg.what) {
                    case MSG_0x12:
// fromJson 将json字符串转为bean对象
                        dinnerBean = new Gson().fromJson((String) msg.obj, DinnerBean.class);
                        String menu[] = dinnerBean.getMenuInfo().getMenu().split("\n");
                        if (menu != null && menu.length > 0) {
                            switch (menu.length) {
                                case 2:
                                    tvMenu1.setText(menu[1].trim());
                                    llMenu2.setVisibility(View.GONE);
                                    break;
                                case 3:
                                    tvMenu1.setText(menu[1].trim());
                                    tvMenu2.setText(menu[2].trim());
                                    break;
                            }

                        }
                        tvDate.setText(dinnerBean.getMenuInfo().getTitle());
                        tv_comment.setText(dinnerBean.getMenuInfo().getMemo());

                        break;
                }

            } catch (Exception e) {

                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dinner, container, false);
        initView(view);

        try {
            initData();
        } catch (Exception e) {
            showToast(e.getMessage());
        }

        return view;
    }


    private void initView(View view) {

        tvDate = (TextView) view.findViewById(R.id.tv_date);
        llMenu1 = (LinearLayout) view.findViewById(R.id.ll_menu1);
        llMenu2 = (LinearLayout) view.findViewById(R.id.ll_menu2);

        tvMenu1 = (TextView) view.findViewById(R.id.tv_menu1);
        tvMenu2 = (TextView) view.findViewById(R.id.tv_menu2);
        tv_comment = (TextView) view.findViewById(R.id.tv3_comment);
        tv_choosed = (TextView) view.findViewById(R.id.tv4_choosed);
        etNo = (EditText) view.findViewById(R.id.et_no);
        etName = (EditText) view.findViewById(R.id.et_name);
        btnOrder = (Button) view.findViewById(R.id.btn_order);


        imgMenu1 = (ImageView) view.findViewById(R.id.img_menu1);
        imgMenu2 = (ImageView) view.findViewById(R.id.img_menu_2);

        llMenu1.setOnClickListener(this);
        llMenu2.setOnClickListener(this);
        btnOrder.setOnClickListener(this);


    }


    private void initData() {
        OkHttpUtils
                .get()
                .url(API.URL_FETCH_ORDER)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        Message message = Message.obtain();
//                        message.obj = response;   //message.obj=bundle  传值也行
//                        message.what = MSG_0x12;
//                        handler.sendMessage(message);
                        dinnerResponse=response;
                        dinnerBean = new Gson().fromJson(response, DinnerBean.class);
                        String menu[] = dinnerBean.getMenuInfo().getMenu().split("\n");
                        if (menu != null && menu.length > 0) {
                            switch (menu.length) {
                                case 2:
                                    tvMenu1.setText(menu[1].trim());
                                    llMenu2.setVisibility(View.GONE);
                                    break;
                                case 3:
                                    tvMenu1.setText(menu[1].trim());
                                    tvMenu2.setText(menu[2].trim());
                                    break;
                            }

                        }
                        tvDate.setText(dinnerBean.getMenuInfo().getTitle());
                        tv_comment.setText(dinnerBean.getMenuInfo().getMemo());
                        EventBus.getDefault().post(MessageWrap.getInstance(dinnerResponse));
                    }

                });

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_menu1:
                tv_choosed.setText(tvMenu1.getText().toString().trim());
                imgMenu1.setImageResource(R.drawable.menu_choosed);
                imgMenu2.setImageResource(R.drawable.menu_unchoosed);

                break;
            case R.id.ll_menu2:
                tv_choosed.setText(tvMenu2.getText().toString().trim());
                imgMenu1.setImageResource(R.drawable.menu_unchoosed);
                imgMenu2.setImageResource(R.drawable.menu_choosed);
                break;
            case R.id.btn_order:
                try {
                    createOrder();
                } catch (Exception e) {
                    showToast(e.getMessage());
                }

                break;
        }
    }

    private void createOrder() {
        String content = tv_choosed.getText().toString().trim();//已选菜单
        String staff = etNo.getText().toString().trim();//工号
        String sign = etName.getText().toString().trim();//姓名
        if (dinnerBean != null) {
            menu = dinnerBean.getMenuInfo().getId();//菜单编号页数
        } else {
            showToast("请检查网络，订餐仅在公司内网wifi下使用");
            return;
        }
        if (content.isEmpty()) {
            showToast("请选择菜单");
            return;
        }
        if (staff.isEmpty()) {
            showToast("请输入工号");
            return;
        }
        if (sign.isEmpty()) {
            showToast("请输入姓名");
            return;
        }

        OkHttpUtils
                .post()
                .url(API.URL_CREAT_ORDER)
                .addParams("menu", menu)
                .addParams("content", content)
                .addParams("staff", staff)
                .addParams("sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        String ss = e.getMessage();
                        builder = new AlertDialog.Builder(getContext())
                                .setTitle("下单失败")
                                .setMessage("失败原因:"+ss).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //ToDo: 你想做的事情
                                    }
                                });
                        builder.create().show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(dinnerResponse)) {
                            EventBus.getDefault().post(MessageWrap.getInstance(dinnerResponse));
                        }

                        ResultBean resultBean = new Gson().fromJson(response, ResultBean.class);

                        builder = new AlertDialog.Builder(getContext())
                                .setTitle(resultBean.getMsg())
                                .setMessage("订单号:"+resultBean.getOrder_id()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        //ToDo: 你想做的事情
                                    }
                                });
                        builder.create().show();

                    }

                });

    }

    //    public void getSyn(final String url) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    //创建OkHttpClient对象
//                    OkHttpClient client = new OkHttpClient();
//                    //创建Request
//                    Request request = new Request.Builder()
//                            .url(url)//访问连接
//                            .get()
//                            .build();
//                    //创建Call对象
//                    Call call = client.newCall(request);
//                    //通过execute()方法获得请求响应的Response对象
//                    Response response = call.execute();
//                    if (response.isSuccessful()) {
//                        //处理网络请求的响应，处理UI需要在UI线程中处理
//                        //...
//
//
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
    public void showToast(String ss) {
        Toast.makeText(getContext(), ss, Toast.LENGTH_SHORT).show();
    }

}